﻿using Abp.Domain.Entities;
using Abp.EntityFramework;
using Abp.EntityFramework.Repositories;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Threading.Tasks;
using WanFang.IRepositories;
using WanFang.Test;

namespace WanFang.EntityFramework.Repositories
{
    public class DynamicFieldRepository: WanFangRepositoryBase<JianCeTemplate>, IDynamicFieldRepository
    {
        public DynamicFieldRepository(IDbContextProvider<WanFangDbContext> dbContextProvider)
            : base(dbContextProvider)
        {

        }

        public async Task CreateField(List<JianCeTemplate> lst)
        {
            int index = 0;
            //字段名称动态生成
            var fieldName = "";
            try
            {
                fieldName = await base.GetDbContext().Database.SqlQuery<string>("select top 1 name from syscolumns where id =object_id(N'jianceitem') and name like 'FField%' order by name desc").FirstOrDefaultAsync();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            if (!string.IsNullOrEmpty(fieldName))
            {
                index=Convert.ToInt32(fieldName.Substring(6,3));
            }
            foreach (var entity in lst)
            {
                index++;
                entity.FField = string.Format("FField{0}", index.ToString("000"));
                //添加
                this.Insert(entity);
                //字段名特殊字符判断
                //类型判断
                if (entity.FieldCategory == "int")
                {
                    base.GetDbContext().Database.ExecuteSqlCommand(string.Format("ALTER TABLE JianCeItem ADD {0} int", entity.FField));
                    continue;
                }
                if (entity.FieldCategory == "varchar")
                {
                    //可以设置字段长度来存放，测试就暂时这么做
                    var lenth = 500;
                    base.GetDbContext().Database.ExecuteSqlCommand(string.Format("ALTER TABLE JianCeItem ADD {0} {1}({2})", entity.FField, "varchar", lenth));
                    continue;
                }
                if (entity.FieldCategory == "date")
                {
                    base.GetDbContext().Database.ExecuteSqlCommand(string.Format("ALTER TABLE JianCeItem ADD {0} datetime", entity.FField));
                    continue;
                }
                throw new Exception("字段类型不匹配，无法添加");
            }
        }

        /// <summary>
        /// 添加质检单据
        /// </summary>
        public void AddJianCeItem(int jianceId, Dictionary<string,string> dic)
        {
            string sqlKey = "";
            string sqlValue = "";
            SqlParameter[] sps = new SqlParameter[dic.Count];
            int index = 0;
            //获取id
            foreach(string key in dic.Keys)
            {
                sqlKey += key + ",";
                sqlValue += "@" + key + ",";
                sps[index] = new SqlParameter("@" + key, dic[key]);
                index++;
            }
            sqlKey = sqlKey.TrimEnd(',');
            sqlValue = sqlValue.TrimEnd(',');
            string sql = "insert into JianCeItem(JianCe_Id," + sqlKey + ")values(" + jianceId + "," + sqlValue + ")";
            base.GetDbContext().Database.ExecuteSqlCommand(sql,sps);
        }
        //add common methods for all repositories
    }
}
